<!--
 * @Author: liaoxing
 * @Date: 2022-02-25 13:59:38
 * @LastEditors: liaoxing
 * @LastEditTime: 2022-03-10 15:49:04
 * @Description: liaoxing created
 * @FilePath: \pin-xin-admin\src\views\myreport\index.vue
-->
<template>
  <div class="myreport">
    <header class="flex-align-center">
      <el-form :inline="true" :model="searchValue" size="mini" v-if="searchValue">
        <el-form-item v-for="i in Object.keys(searchValue)" :label="searchValueLabel[i].title" :key="i">
          <el-date-picker
            v-if="searchValueLabel[i].type === 'month'"
            v-model="searchValue[i]"
            type="month"
            :value-format="'yyyy-MM'"
            placeholder="请选择月份">
          </el-date-picker>
          <el-date-picker
            v-else-if="searchValueLabel[i].type === 'date'"
            v-model="searchValue[i]"
            type="month"
            :value-format="'yyyy-MM-dd'"
            placeholder="请选择日期">
          </el-date-picker>
          <el-input v-else v-model="searchValue[i]"></el-input>

        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getReportDetail">查 询</el-button>
          <el-button @click="reset">重 置</el-button>
        </el-form-item>
      </el-form>
      <el-button size="mini" type="primary" @click="exportReport">导 出</el-button>
    </header>
    <main>
      <el-table
        v-loading="loadingPage"
        :data="tableData"
        border
        height="870"
        :show-header="false"
        :span-method="objectSpanMethod"
        :cell-style="setCellStyle"
        style="width: 100%">
        <el-table-column
          v-for="(item, index) in tableCols"
          :key="'tableCols' + index + item"
          :width="colWidthList[index + ''] ? colWidthList[index + ''].width : 'auto'"
          :prop="item">
          <template slot-scope="scope">
            <el-popover
              placement="top-start"
              trigger="click"
              :content="scope.row[item]">
              <div class="more" slot="reference">
                {{ judgeDateFormat(scope.row[item], scope.$index, scope.column.property * 1) }}
              </div>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
    </main>
    <footer class="flex-align-center" v-if="showPagination">
      <el-pagination        
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="pageNo"
        :page-sizes="[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalSize">
      </el-pagination>
    </footer>
  </div>
</template>

<script>
import report from "@/api/report/newApi"
import styleInfo from "@/constant/styleInfo.json"
import downLoad from "@/utils/downBase64"
import timeTrans from "@/utils/timeTrans"
export default {
  name: "myreport",
  data () {
    return {
      tableInfo: null,
      tableData: [],
      tableCols: [],
      tableData: null,
      tableStyleData: null,
      colWidthList: null,
      loadingPage: false,
      searchValue: null,
      pageNo: 1,
      pageSize: 10,
      totalSize: 0,
      searchValueLabel: {},
      params: {},
      showPagination: false,
      reportId: null
    }
  },
  created () {
    const hash = window.location.pathname.split('/')
    const length = hash.length
    this.reportId = hash[length-1]
  },
  mounted () {
    this.getReportName()
  },
  methods: {
    /* 判断日期数据格式 */
    judgeDateFormat (item, rowIndex, colIndex) {
      if (!this.tableStyleData[rowIndex][colIndex] || !this.tableStyleData[rowIndex][colIndex].style || (!item.trim())) {
        return item
      }
      let format = null
      if (this.tableStyleData[rowIndex][colIndex].style.format) {
        format = this.tableStyleData[rowIndex][colIndex].style.format
      }
      let value = ''
      switch (format) {
        case 'number':
          value = item
          break
        case 'date':
          value = timeTrans.getYMD(new Date(item).getTime(), '/')
          break
        case 'date2':
          value = timeTrans.getYMDCH(new Date(item).getTime())
          break
        default: 
          value = item
      }
      return value
    },
    /* 导出报表 */
    exportReport () {
      let param = {
        excelConfigId: this.reportId,
        queryParam: {
          pageNo: this.pageNo,
          pageSize: this.pageSize
        }
      }

      for(let i in this.searchValue) {
        param.queryParam[i] = this.searchValue[i]
      }

      report.exportAllExcel(param)
        .then(res => {
          if (res.code === 200) {
            downLoad('data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,' + res.result.file, res.result.name)
          }else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    },
    /* 重置 */
    reset () {
      this.getReportName()
    },
    /* handleSizeChange */
    handleSizeChange (val) {
      this.pageSize = val
      this.getReportDetail()
    },
    /* handleCurrentChange */
    handleCurrentChange () {
      this.getReportDetail()
    },
    /* 获取项目名称 */
    getReportName () {
      this.loadingPage = true
      report.getQueryInfo({reportId: this.reportId, param: '{}'})
        .then(res => {
          if (res.code === 200) {
            let temp = {}
            res.result.list.forEach(item => {
              temp[item.name] = item.defaultValue
              this.searchValueLabel[item.name] = {title: item.title, type: item.realType}
            })
            this.searchValue = JSON.parse(JSON.stringify(temp))
            this.getReportDetail()
          }else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    },
    /* 获取报表详情 */
    getReportDetail () {
      this.loadingPage = true
      const param = {
        id: this.reportId,
        params: {
          pageNo: this.pageNo,
          pageSize: this.pageSize
        }
      }

      for(let i in this.searchValue) {
        param.params[i] = this.searchValue[i]
      }

      param.params = JSON.stringify(param.params)

      report.queryReportDetails(param)
        .then(res => {
          if (res.code === 200) {
            const searchData = res.result.result.dataList.replaceParams
            const dataList = res.result.result.dataList
            for (const i in dataList) {
              if (dataList[i].count) {
                this.totalSize = dataList[i].count
                this.showPagination = dataList[i].isPage * 1
              }
            }
            for(const i in searchData) {
              switch (i) {
                case "pageNo":
                  this.pageNo = searchData[i] * 1
                  break
                case "pageSize":
                  this.pageSize = searchData[i] * 1
                  break
              }
            }
            this.tableInfo = JSON.parse(res.result.result.jsonStr)
            this.renderTable()
          }else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    },
    /* 渲染表格 */
    renderTable () {
      const {rows, styles, cols} = this.tableInfo
      const rowsKeys = Object.keys(rows)
      let newStyleInfo = []
      let newDataInfo = []
      this.colWidthList = cols
      rowsKeys.forEach(item => {
        if (!rows[item]['cells']) return
        const cellsData = rows[item]['cells']
        let keys = Object.keys(cellsData)
        let tempDataInfo = {}
        let tempStyleInfo = []
        keys.forEach(i => {
          if (cellsData[i].display == "number") {
            tempDataInfo[i] = (cellsData[i].text * 1).toFixed(cellsData[i].decimalPlaces * 1)
          } else {
            tempDataInfo[i] = cellsData[i].text
          }
          tempStyleInfo[i] = {}
          if (cellsData[i].merge) {
            tempStyleInfo[i].merge = this.judgeMerge(cellsData[i].merge, item, i)
            for(let l = 0; l < cellsData[i].merge[1]; l++) {
              tempDataInfo[i * 1 + l + 1 + ''] = ''
            }
          }
          if (cellsData[i].style || cellsData[i].style === 0 ) {
            // tempStyleInfo[i].style = this.judgeStyle(cellsData[i].style)
            tempStyleInfo[i].style = this.getElementAttr(styles[cellsData[i].style])
          }
        })
        newStyleInfo.push(tempStyleInfo)
        newDataInfo.push(tempDataInfo)
      })
      let colsKeys = Object.keys(newDataInfo[0])
      for(let i = 0; i < newDataInfo.length; i++) {
        if (colsKeys.length < Object.keys(newDataInfo[i]).length) {
          colsKeys = Object.keys(newDataInfo[i])
        }
      }
      this.tableCols = colsKeys
      this.tableData = newDataInfo
      this.tableStyleData = newStyleInfo
    },
    /* 判断merge */
    judgeMerge (merge, rows, cols) {
      return {
        rows: rows,
        cols: cols,
        colsMerge: merge
      }
    },
    /* 获取标签属性 */
    getElementAttr (style) {
      let temp = {}
      for (let i in style) {
        switch (i) {
          case "font":
            for (let i2 in style[i]) {
              switch (i2) {
                case "bold":
                  temp["fontWeight"] = "bold"
                  break
                case "size":
                  temp["fontSize"] = style[i].size + 'px'
                  break
              }
            }
            break
          case "align": 
            temp['textAlign'] = style.align
            break
          case "format":
            temp['format'] = style.format
            break
          default:
            Object.assign(temp, styleInfo[i])
        }
      }
      return temp
    },
    /* 单元格合并 */
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      let item = this.tableStyleData[rowIndex]
      for(let i = 0; i < item.length; i++) {
        let info = item[i]
        if (info && info.merge) {
          const merge = info.merge
          if (columnIndex == merge.cols) {
            return {
              rowspan: 1,
              colspan: merge.colsMerge[1] + 1
            }
          }
          if (columnIndex > merge.cols * 1 && columnIndex <= merge.cols * 1 + merge.colsMerge[1]) {
            return {
              rowspan: 1,
              colspan: 0
            }
          }
        }
      }
      if(rowIndex == this.tableStyleData.length - 1) {
        this.loadingPage = false
      }
    },
    /* 单元格样式 */
    setCellStyle ({row, column, rowIndex, columnIndex}) {
      let item = this.tableStyleData[rowIndex]
      if (item[columnIndex] && item[columnIndex].style) {

        if (columnIndex == 0 && item[columnIndex].style.borderColor) {
          item[columnIndex].style['borderLeft'] = "1px solid #dfe6ec"
        }
        
        if(item[columnIndex].style.borderColor) {
          if (rowIndex == 0) {
            item[columnIndex].style['borderTop'] = "1px solid #dfe6ec"
          }
          if (columnIndex == 0) {
            item[columnIndex].style['borderLeft'] = "1px solid #dfe6ec"
          }

          if (rowIndex > 0) {
            let lastItem = this.tableStyleData[rowIndex - 1]
            if (lastItem[columnIndex] && (!lastItem[columnIndex].style || !lastItem[columnIndex].style.borderColor)) {
              item[columnIndex].style['borderTop'] = "1px solid #dfe6ec"
            }
            if (!lastItem[columnIndex]) {
              item[columnIndex].style['borderTop'] = "1px solid #dfe6ec"
            }
          }
        }

        
        return item[columnIndex].style
      }
    }
  }
}
</script>

<style lang="less">
.myreport{
  width: 100%;
  height: calc(100vh - 85px);
  position: relative;
  box-sizing: border-box;
  padding: 16px;
  background-color: #f3f5fa;
  // overflow: scroll;
  header, footer{
    width: 100%;
    height: 60px;
    background-color: white;
    box-sizing: border-box;
    margin-bottom: 15px;
    padding: 0 16px;
    .el-form-item{
      margin-bottom: unset !important;
    }
  }
  footer {
    justify-content: end;
    margin-bottom: 0px;
    margin-top: 15px;
  }
  main{
    width: 100%;
    height: calc(100% - 150px);
    box-sizing: border-box;
    padding: 16px;
    background-color: white;
    // overflow-y: auto;
    .el-table{
      // overflow: hidden;
      height: 100% !important;
      &::before, &::after{
        background: unset;
      }
      .el-table__body-wrapper{
        overflow-y: auto;
      }
    }
    .el-table--border,
    .el-table--group {
      // border-color: rgb(168, 168, 168);
      border-color: transparent;
    }
    
    .el-table--border:after,
    .el-table--group:after,
    .el-table:before {
      // background-color: rgb(168, 168, 168);
      border-color: transparent;
    }
    
    .el-table td,
    .el-table--border th,
    .el-table th.is-leaf {
      // border-bottom-color: rgb(168, 168, 168);
      border-color: transparent;
    }
    
    .el-table--border td,
    .el-table--border th {
      // border-right-color: rgb(168, 168, 168);
      border-color: transparent;
    }
  }
}
</style>